﻿window.MakeOrder = Backbone.Model.extend({
    urlRoot: 'api/order/',
    url: function () {
        return this.urlRoot;
    },
    parse: function (model) {
        if (model instanceof MakeOrder) {
            var orderPrice = model.ProductPrice + model.DispatchPrice + model.InvoiceTax + model.PackPrice + model.BlessCardPrice
            + model.InsurePrice + model.PaymentPrice - model.Discount;
            model.orderPrice = orderPrice.toFixed(4);
            model.ShouldPayPrice = model.ShouldPayPrice.toFixed(2);
        }
        return model;
    }
});

window.MakeOrderView = Backbone.View.extend({
    el: '#jqt',
    initialize: function () {
        this.template = $('#OrderMakeTemplate').html();
        this.addressList = new AddressList();
        this.payments = new PaymentList();
        this.dispatchmodeList = new DispatchModeList();
    },
    events: {
        'click .ordermake ul.address': 'goToAddressList',
        'click .ordermake ul.payment': 'goToPaymentList',
        'click .ordermake ul.dispatchmode': 'goToDispatchModeList',
        'click .ordermake ul.invoice': 'goToInvoice',
        'click .ordermake ul.coupon': 'goToCoupon',
        'click .ordermake #PayCartBtn': 'generateOrder'
    },
    render: function () {
        var that = this;
        var partial = { header: $('#HeaderTemplate').html(), footer: $('#FooterTemplate').html(),
            innerFooter: $('#InnerFooterTemplate').html()
        };
        var data = { hasBack: true, title: "取消", btnListR: [{ name: 'home'}] };
        this.$el.append(Mustache.render(this.template, data, partial));

        this.fetchAddress();

        this.fetchPayment();

        this.fetchDispatchMode();

        this.setInvoiceContent();

        this.setCoupon();

        window.setTimeout(function () { that.caculatePrice(); }, 500);

        return this;
    },

    goToAddressList: function () {
        $('#PayCartBtn').addClass('ui-button-disable');
        pageView.goTo('AddressList');
    },

    goToPaymentList: function () {
        $('#PayCartBtn').addClass('ui-button-disable');
        pageView.goTo('PaymentList');
    },

    goToDispatchModeList: function () {
        $('#PayCartBtn').addClass('ui-button-disable');
        pageView.goTo('DispatchModeList');
    },

    goToInvoice: function () {
        $('#PayCartBtn').addClass('ui-button-disable');
        pageView.goTo('MyInvoice');
    },
    goToCoupon: function () {
        $('#PayCartBtn').addClass('ui-button-disable');
        pageView.goTo('CouponList');
    },
    getOrderNo: function () {
        var orderno = '';
        $.ajax({
            url: 'api/getorderno',
            dataType: 'json',
            async: false,
            success: function (res) {
                orderno = res;
            }
        });
        return orderno;
    },

    setOrderParameter: function () {
        var address = JSON.parse(localStorage.getItem('addressItem')),
            carts = JSON.parse(localStorage.getItem('cartItems')),
            invoice = localStorage.getItem('invoiceitem') ? JSON.parse(localStorage.getItem('invoiceitem')) : null,
            coupon = localStorage.getItem('couponitem') ? JSON.parse(localStorage.getItem('couponitem')) : null,
            paymentid = localStorage.getItem('paymentid'),
            allPrice = localStorage.getItem('allPrice'),
            dispatchmodeid = localStorage.getItem('dispatchmodeid');
        regionCode = localStorage.getItem('regionCode') || '1';
        var order = new MakeOrder();
        if (carts) {
            if (address == null) {
                address = {};
            }
            if (allPrice && address && paymentid && dispatchmodeid) {
                order.set({
                    ProductList: carts,
                    Name: address.NAME,
                    Email: address.Email,
                    RegionCode: regionCode,
                    Address: address.Address,
                    Postalcode: address.Postalcode,
                    Tel: address.Tel,
                    Mobile: address.Mobile,
                    DispatchModeGuid: dispatchmodeid,
                    PaymentGuid: paymentid,
                    ProductPrice: +allPrice,
                    ShouldPayPrice: +allPrice,
                    OutOfStockOperate: $('#order_outofstock').val(),
                    ClientToSellerMsg: $('#order_remark').val()
                });
                if (invoice) {
                    order.set({
                        InvoiceType: invoice.InvoiceType,
                        InvoiceTitle: invoice.InvoiceHeader,
                        InvoiceContent: invoice.InvoiceContent
                    });
                }
                if (coupon) {
                    order.set({
                        UsedFavourTicket: coupon.ticketcode,
                        ActivityGuid: coupon.activityGuid
                    });
                }
                return order;
            }
            return '';
        }
        return null;
    },

    caculatePrice: function () {
        var that = this,
            order = this.setOrderParameter();
        //        if (order == 'address null') {
        //            alert('增加收货地址!'); pageView.scrollToTop(); return;
        //        }
        if (order && order instanceof MakeOrder) {
            order.url = 'api/order/price/caculate';
            order.set({ id: 1 });
            order.save('', '', {
                success: function (model, res) {
                    var template = $('#CalculatePriceTemplate').html();
                    localStorage.setItem('shouldPay', order.get('ShouldPayPrice'));
                    $('.ordermake .pay-cart').html(Mustache.render(template, order.toJSON(), []));
                    pageView.resizeScroll();
                }
            });
        }
    },

    generateOrder: function (e) {
        var target = $(e.currentTarget);
        var address = localStorage.getItem('addressid');
        if (address == null || address == "-1" || address == undefined) {
            alert('请先填写收货地址信息，确保订单正确!');
            pageView.scrollToTop();
            return;
        }
        var order = this.setOrderParameter();
        var orderNo = this.getOrderNo();
        if (order && order !== '') {
            order.set({ OrderNumber: orderNo });
            order.save('', '', {
                success: function (model, res) {
                    if (res && res == 201) {
                        localStorage.setItem('orderno', orderNo);
                        pageView.goTo('GenerateOrder');
                        localStorage.removeItem('cartItems');
                        localStorage.removeItem('addressItem');
                        localStorage.removeItem('addressid');
                        localStorage.removeItem('couponitem');
                        localStorage.removeItem('dispatchmodeid');
                        localStorage.removeItem('invoiceitem');
                        localStorage.removeItem('paymentid');
                        localStorage.removeItem('allPrice');
                    }
                    else
                        pageView.goTo('ErrorPage');
                }
            });
        } else if (order == '') {
            $('#OrderMakeError').html('订单信息不全');
            return;
        } else {
            pageView.goTo('GenerateOrder');
        }
    },
    fetchAddress: function () {
        var that = this;
        this.addressList.fetch({
            success: function () {
                if (that.addressList.length > 0) {
                    var sampleTemplate = $('#OrderMakeAddressTemplate').html(),
                    address = that.addressList.toJSON()[0],
                    addressid = localStorage.getItem('addressid');
                    if (addressid && addressid != "-1") {
                        address = _.find(that.addressList.toArray(), function (addr) {
                            return addr.get('Guid') == addressid;
                        }).toJSON();
                        localStorage.setItem('addressid', address.Guid);
                        localStorage.setItem('addressItem', JSON.stringify(address));
                    } else {
                        localStorage.setItem('addressid', that.addressList.toJSON()[0].Guid);
                        localStorage.setItem('addressItem', JSON.stringify(that.addressList.toJSON()[0]));
                    }
                    pageView.resizeScroll();
                    $('.ordermake .address').html(Mustache.render(sampleTemplate, address, []));
                    AddressListView.renderList(that.addressList.toJSON());
                } else {
                    $('.ordermake .address').html('<li>暂无收货信息，请填写<span class="menu-botton-arrow"></span></li>');
                }
            }
        });
    },

    fetchPayment: function () {
        var that = this;
        this.payments.fetch({
            success: function () {
                var template = $('#OrderMakePaymentTemplate').html(),
                    paymentid = localStorage.getItem('paymentid'),
                    payment = that.payments.toJSON()[0];
                if (paymentid && paymentid != -1) {
                    payment = _.find(that.payments.toArray(), function (pay) {
                        return pay.get('Guid') == paymentid;
                    }).toJSON();
                    localStorage.setItem('paymentid', payment.Guid);
                    localStorage.setItem('paymentstyle', payment.NAME);
                } else {
                    localStorage.setItem('paymentid', that.payments.toJSON()[0].Guid);
                    localStorage.setItem('paymentstyle', that.payments.toJSON()[0].NAME);
                }
                pageView.resizeScroll();
                $('.ordermake .payment').html(Mustache.render(template, payment, []));
                PaymentView.renderPaymentHidden(that.payments.toJSON());
            }
        });
    },

    fetchDispatchMode: function () {
        var that = this;
        this.dispatchmodeList.fetch({
            success: function () {
                var template = $('#OrderMakeDispatchModeTemplate').html(),
                    dispatchmodeid = localStorage.getItem('dispatchmodeid'),
                    dispatchmode = that.dispatchmodeList.toJSON()[0];
                if (dispatchmodeid && dispatchmodeid != -1) {
                    dispatchmode = _.find(that.dispatchmodeList.toArray(), function (mode) {
                        return mode.get('Guid') == dispatchmodeid;
                    }).toJSON();
                    localStorage.setItem('dispatchmodeid', dispatchmode.Guid);
                } else {
                    localStorage.setItem('dispatchmodeid', that.dispatchmodeList.toJSON()[0].Guid);
                }
                pageView.resizeScroll();
                $('.ordermake .dispatchmode').html(Mustache.render(template, dispatchmode, []));
                DispatchView.renderDispatchHidden(that.dispatchmodeList.toJSON());
            }
        });
    },
    setInvoiceContent: function () {
        var invoice = localStorage.getItem('invoiceitem');
        if (invoice) {
            var invoiceItem = JSON.parse(invoice);
            if (!invoiceItem.HasInvoice || invoiceItem.HasInvoice == 'false') {
                $('.ordermake ul.invoice').html('<li>不开据发票<span class="menu-botton-arrow"></span></li>');
            } else {
                $('.ordermake ul.invoice').html(Mustache.render($('#OrderMakeInvoiceTemplate').html(), invoiceItem, []));
            }
        }
    },
    setCoupon: function () {
        var coupon = localStorage.getItem('couponitem');
        if (coupon && coupon != "-1") {
            var couponItem = JSON.parse(coupon);
            if (couponItem.ticketcode)
                $('ul.coupon li').html('优惠券<p>使用：' + couponItem.couponname + ',' + couponItem.ticketcode + '</p><span class="menu-botton-arrow"></span>');
            else
                $('ul.coupon li').html('优惠券<p>使用：' + couponItem.couponname + '</p><span class="menu-botton-arrow"></span>');
        }
        else {
            $('ul.coupon li').html('优惠券<span class="menu-botton-arrow"></span>');
        }
    }
});